#include <stdio.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_io.h"
#include "iot_pwm.h"
#include "hi_pwm.h"
#include "hi_time.h"

int count1 = 0;
static const uint16_t g_tuneFreqs[] = {
    0,

    38223,
    34052,
    30338,
    28635,
    25511,
    22728,
    20249,
    51021,
    45454,
    40495,

};
static const uint8_t g_scoreNotes[] = {
    2, 2, 3, 2, 5, 4,
    2, 2, 3, 2, 6, 5,
    2, 2, 8, 6, 5, 4, 3,
    7, 7, 6, 5, 4, 3,
};
static const uint8_t g_scoreDurations[] = {
    4, 4, 4, 4, 4, 8,
    4, 4, 4, 4, 4, 8,
    4, 4, 4, 4, 4, 4, 8,
    4, 4, 4, 4, 4, 8
};

// 初始化蜂鸣器
static void beepInit()
{
    hi_gpio_init();
    hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_PWM2_OUT);
    hi_io_set_pull(HI_IO_NAME_GPIO_11, HI_IO_PULL_UP);

    hi_pwm_init(HI_PWM_PORT_PWM2);
    hi_pwm_set_clock(PWM_CLK_XTAL);
}

// 初始化呼吸灯
static void breathingLightInit()
{
    hi_gpio_init();
    hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_PWM1_OUT);
    hi_io_set_pull(HI_IO_NAME_GPIO_10, HI_IO_PULL_UP);

    hi_pwm_init(HI_PWM_PORT_PWM1);
    hi_pwm_set_clock(PWM_CLK_XTAL);
}

// 蜂鸣器播放任务
static void beepSingTask(void *arg)
{
    uint32_t tune;
    uint16_t freqDivisor;
    uint32_t tuneInterval;

    beepInit();

    for (size_t i = 0; i < sizeof(g_scoreNotes) / sizeof(g_scoreNotes[0]); i++)
    {
        tune = g_scoreNotes[i];
        freqDivisor = g_tuneFreqs[tune];
        tuneInterval = g_scoreDurations[i] * (125 * 1000);
        printf("num=%d, freqDivisor=%d\n", i, freqDivisor);
        hi_pwm_start(HI_PWM_PORT_PWM2, freqDivisor / 2, freqDivisor);

        hi_udelay(tuneInterval);
        hi_pwm_stop(HI_PWM_PORT_PWM2);
    }
}

// 呼吸灯任务
static void breathingLightTask(void *arg)
{
    breathingLightInit();
    uint16_t dutyCycle;
    while (1) {
        // 亮度逐渐增加
        for (dutyCycle = 0; dutyCycle <= 1000; dutyCycle += 10) {
            hi_pwm_start(HI_PWM_PORT_PWM1, dutyCycle, 1000);
            hi_udelay(20000);
        }
        // 亮度逐渐减小
        for (dutyCycle = 1000; dutyCycle > 0; dutyCycle -= 10) {
            hi_pwm_start(HI_PWM_PORT_PWM1, dutyCycle, 1000);
            hi_udelay(20000);
        }
    }
}

// 主入口函数
static void MainEntry(void)
{
    osThreadAttr_t beepAttr = {0};
    beepAttr.name = "beepSingTask";
    beepAttr.stack_size = 4096 * 2;
    beepAttr.priority = osPriorityNormal;
    if (osThreadNew(beepSingTask, NULL, &beepAttr) == NULL)
    {
        printf("[GpioEntry] create beepSingTask failed!\n");
    }

    osThreadAttr_t lightAttr = {0};
    lightAttr.name = "breathingLightTask";
    lightAttr.stack_size = 4096 * 2;
    lightAttr.priority = osPriorityNormal;
    if (osThreadNew(breathingLightTask, NULL, &lightAttr) == NULL)
    {
        printf("[GpioEntry] create breathingLightTask failed!\n");
    }
}

SYS_RUN(MainEntry);    
